//
//  SetAppViewController.m
//  PlayCatchGame
//
//  Created by 流言 on 2018/2/1.
//  Copyright © 2018年 清正. All rights reserved.
//

#import "SetAppViewController.h"
#import "AppHeader.h"
#import "AppSetCell.h"

@interface SetAppViewController () <UITableViewDelegate, UITableViewDataSource> {
    NSString *cacheSize;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *dataArray;
@property (strong, nonatomic) UIView *footTableView;

@end

@implementation SetAppViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    cacheSize =[NSString stringWithFormat:@"%.2fM", [self getCacheSize]];
    self.dataArray =@[@[@{@"title":@"背景音乐", @"cellType":@"switch"},
                        @{@"title":@"按键音效", @"cellType":@"switch"}],
                      @[@{@"title":@"接受系统通知", @"cellType":@"switch"}],
                      @[@{@"title":@"关于我们", @"cellType":@"null"},
                        @{@"title":@"清理缓存", @"cellType":@"left_label"}]].mutableCopy;
    self.tableView.tableFooterView =self.footTableView;
}

- (UIView *)footTableView {
    if (!_footTableView) {
        _footTableView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 150)];
        _footTableView.backgroundColor =[UIColor clearColor];
        
        UIButton *logoutButton =[UIButton buttonWithType:UIButtonTypeCustom];
        logoutButton.frame =CGRectMake(0, (CGRectGetHeight(_footTableView.frame)-50)/2.0, KScreenWidth, 50);
        [logoutButton setTitle:@"退 出" forState:UIControlStateNormal];
        [logoutButton setTitleColor:[UIColor colorWithRed:0.27 green:0.27 blue:0.27 alpha:1.00] forState:UIControlStateNormal];
        logoutButton.backgroundColor =[UIColor whiteColor];
        [logoutButton addTarget:self action:@selector(logoutButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_footTableView addSubview:logoutButton];
    }
    return _footTableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *contentArray =self.dataArray[section];
    return contentArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 10)];
    headerView.backgroundColor =tableView.backgroundColor;
    return headerView;
}

- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 0.1)];
    footerView.backgroundColor =tableView.backgroundColor;
    return footerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AppSetCell *cell =[tableView dequeueReusableCellWithIdentifier:@"AppSetCell"];
    if (!cell) {
        cell =[AppSetCell findCellWithIdentifier:@"AppSetCell"];
    }
    NSDictionary *contentDict =self.dataArray[indexPath.section][indexPath.row];
    if ([contentDict[@"cellType"] isEqualToString:@"switch"]) {
        cell.accessoryType =UITableViewCellAccessoryNone;
        cell.contentLabel.hidden =YES;  cell.rightSwitch.hidden =NO;
        [cell.rightSwitch setOn:YES animated:YES];
    } else if ([contentDict[@"cellType"] isEqualToString:@"null"]) {
        cell.accessoryType =UITableViewCellAccessoryDisclosureIndicator;
        cell.contentLabel.hidden =YES;  cell.rightSwitch.hidden =YES;
    } else if ([contentDict[@"cellType"] isEqualToString:@"left_label"]) {
        cell.accessoryType =UITableViewCellAccessoryDisclosureIndicator;
        cell.contentLabel.hidden =NO;  cell.rightSwitch.hidden =YES;
    }
    cell.titleLabel.text =contentDict[@"title"];
    if ([cell.titleLabel.text containsString:@"清理缓存"]) {
        cell.contentLabel.text =cacheSize;
    }
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
   
    AppSetCell *cell =[tableView cellForRowAtIndexPath:indexPath];
    if ([cell.titleLabel.text containsString:@"清理缓存"]) {
        [self jxt_showAlertWithTitle:@"提示" message:@"是否清理缓存?" appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
            alertMaker.addActionCancelTitle(@"取消").addActionDefaultTitle(@"清理");
        } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
            if (buttonIndex == 1) {
                [self removeCache];
            }
        }];
    }
}
/// 移除缓存
- (void)removeCache {
    NSString*cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)objectAtIndex:0];
    //返回路径中的文件数组
    NSArray *files = [[NSFileManager defaultManager]subpathsAtPath:cachePath];
    for(NSString *p in files) {
        NSError*error;
        
        NSString*path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@", p]];
        
        if([[NSFileManager defaultManager]fileExistsAtPath:path]) {
            BOOL isRemove = [[NSFileManager defaultManager]removeItemAtPath:path error:&error];
            if(isRemove) {
                cacheSize =[NSString stringWithFormat:@"%.2fM", [self getCacheSize]];
                [self.tableView reloadData];
                [AppToast showFileWithString:@"清理成功" OffsetY:50];
            } else {
                [AppToast showFileWithString:@"清理失败" OffsetY:50];
            }
        }
    }
}
/// 获取缓存大小
- (CGFloat)getCacheSize {
    CGFloat folderSize = 0.0;
    //获取路径
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) firstObject];
    //获取所有文件的数组
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    for(NSString *path in files) {
        NSString *filePath = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@", path]];
        folderSize = folderSize + [[NSFileManager defaultManager]attributesOfItemAtPath:filePath error:nil].fileSize;
    }
    //转换为M为单位
    CGFloat sizeM = folderSize /1024.0/1024.0;
    
    return sizeM;
}

- (void)logoutButtonClick:(UIButton*)button {
    [LoginViewController gotoLoginViewController:self loginType:^(BOOL isSuccess) {
        if (isSuccess) {
            [TheGlobalMethod insertUserDefault:@"" Key:@"code"];
            [TheGlobalMethod insertUserDefault:@"" Key:@"token"];
        }
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
